package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 用来完成处理请求的环节
 */
public class DispatcherServlet {
    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getUri();
        System.out.println("请求的抽象路径:"+path);

        File file = new File("./webapps" + path);

        if(file.isFile()){
            response.setContentFile(file);
            String fileName = file.getName();
            String[] data = fileName.split("\\.");
            Map<String,String> map = new HashMap<>();
            map.put("html","text/html");
            map.put("css","text/css");
            map.put("js","application/javascript");
            map.put("png","image/png");
            map.put("jpg","image/jpeg");



            response.addHeader("Content-Type",map.get(data[data.length-1]));
            response.addHeader("Content-Length",file.length()+"");
        }else{
            response.setStatusCode(404);
            response.setStatusReason("No Found");
            file = new File("./webapps/root/404.html" );
            response.setContentFile(file);
            response.addHeader("Content-Type","text/html");
            response.addHeader("Content-Length",file.length()+"");
        }

        response.addHeader("Server","WebServer");

    }
}
